import { useState, useEffect } from 'react';
import { ProFormText, ProFormDateTimePicker } from '@ant-design/pro-components';
import { ProForm } from '@ant-design/pro-components';
import { Button, Table, Form, Tooltip, Modal, message } from 'antd';
import { history } from 'umi';
import { PageContainer } from '@ant-design/pro-components';
import { profileActivate, profileSearchWithPage } from '@/services/profile';
import styles from './style.less';

const { confirm } = Modal;

const ProfileList: React.FC = () => {
  const [spining, setSpining] = useState(false);
  const [pageNo, setPageNo] = useState(1);
  const [pageSize, setPageSize] = useState(20);
  const [total, setTotal] = useState(1);
  const [dataSource, setDataSource] = useState([] as API.ProfileListItem[]);
  const [form] = Form.useForm();

  // 获取列表
  const getList = async () => {
    console.log('from', form.getFieldsValue());
    const formValue = form.getFieldsValue();
    const param: API.ProfileSearchInfo = {
      ...formValue,
      pageNo: pageNo,
      pageSize: pageSize,
    };
    setSpining(true);
    const { code, data } = await profileSearchWithPage(param);
    // const { code, data } = res || {};
    setSpining(false);
    if (code === 200 && data) {
      const arr: API.ProfileListItem[] = [];
      data.rows.forEach((item: any) => {
        arr.push({
          ...item.realProfileInfo,
        });
      });
      setDataSource(arr);
      setTotal(data.totalCount);
    }
    return {};
  };

  useEffect(() => {
    getList();
  }, [pageNo, pageSize]);

  // 跳转新增页
  const hanldleAdd = () => {
    history.push(`/profile/detail/add`);
  };

  // 跳编辑页
  const hanldleEdit = (record: any) => {
    history.push(`/profile/detail/modify/${record.activityId}`);
  };

  // 跳编辑页---复制
  const hanldleCopy = (record: any) => {
    history.push(`/profile/detail/add/${record.activityId}`);
  };

  // 提交
  const handleOperate = (record: any, type: string) => {
    confirm({
      // title: '提醒',
      // icon: <ExclamationCircleOutlined style={{ color: '#3D50D6' }} />,
      content: `确认${type}活动：${record.activityId}？`,
      async onOk() {
        const params = {
          activityIds: record.activityId,
        };
        try {
          const { code, data } = await profileActivate({ ...params });
          if (code === 200 && data) {
            message.success('操作成功');
            getList();
          } else {
            // message.error(msg);
          }
        } catch (error) {}
      },
      onCancel() {},
    });
  };

  const columns = [
    {
      title: '活动定义',
      dataIndex: 'activityId',
      key: 'activityId',
      width: 200,
      ellipsis: true,
      render: (text: any, record: any) => (
        <Tooltip key={record.activityId} title={record.activityId || ''} placement="topLeft">
          {record.activityId}
        </Tooltip>
      ),
    },
    {
      title: '活动组',
      dataIndex: 'activityGroup',
      key: 'activityGroup',
      width: 200,
    },
    {
      title: '给顾客开票支付ID',
      dataIndex: 'paymentIdA',
      key: 'paymentIdA',
      width: 220,
    },
    {
      title: '给第三方开票支付ID',
      dataIndex: 'paymentIdB',
      key: 'paymentIdB',
      width: 220,
    },
    {
      title: '活动组批次',
      dataIndex: 'activityGroupRound',
      key: 'activityGroupRound',
      width: 220,
    },
    {
      title: '券名',
      dataIndex: 'activity',
      key: 'activity',
      width: 220,
      ellipsis: true,
      render: (text: any, record: any) => (
        <Tooltip key={record.activityId} title={record.activity || ''} placement="topLeft">
          {record.activity}
        </Tooltip>
      ),
    },
    {
      title: '品牌',
      dataIndex: 'brandName',
      key: 'brandName',
      width: 120,
    },
    {
      title: '发放平台',
      dataIndex: 'placeChannelName',
      key: 'placeChannelName',
      width: 200,
    },
    {
      title: '发放形式',
      dataIndex: 'placeStyle',
      key: 'placeStyle',
      width: 120,
    },
    {
      title: '券类型',
      dataIndex: 'couponTypeName',
      key: 'couponTypeName',
      width: 120,
    },
    {
      title: '宅急送优惠CODE',
      dataIndex: 'onlineCode',
      key: 'onlineCode',
      width: 220,
    },
    {
      title: '发放电子券数量',
      dataIndex: 'count',
      key: 'count',
      width: 200,
    },
    {
      title: '券净值',
      dataIndex: 'sales',
      key: 'sales',
      width: 100,
    },
    {
      title: '活动开始时间',
      dataIndex: 'activityStartTime',
      key: 'activityStartTime',
      width: 220,
    },
    {
      title: '活动结束时间',
      dataIndex: 'activityEndTime',
      key: 'activityEndTime',
      width: 220,
    },
    {
      title: '主档状态',
      dataIndex: 'profileStatus',
      key: 'profileStatus',
      width: 220,
    },
    {
      title: '使用规则类型',
      dataIndex: 'useRuleTypeName',
      key: 'useRuleTypeName',
      width: 220,
      ellipsis: true,
      render: (text: any, record: any) => (
        <Tooltip key={record.activityId} title={record.useRuleTypeName || ''} placement="topLeft">
          {record.useRuleTypeName}
        </Tooltip>
      ),
    },
    {
      title: '操作',
      key: 'operation',
      fixed: 'right',
      width: 150,
      align: 'left',
      render: (text: any, record: any) => (
        <div key={record.activityId}>
          {/* <Button onClick={() => handleOperate(record, '提交')} type="primary">
            提交生成Activity
          </Button>
          &nbsp;&nbsp;
          <Button onClick={() => handleOperate(record, '提交')} type="primary">
            编辑子规则
          </Button>
          &nbsp;&nbsp;
          <Button onClick={() => handleOperate(record, '提交')} type="primary">
            同步至UAT
          </Button>
          &nbsp;&nbsp;
          <Button onClick={() => handleOperate(record, '提交')} type="primary">
            复制Profile
          </Button>
          &nbsp;&nbsp; */}
          <a onClick={() => hanldleEdit(record)}>编辑</a>&nbsp;&nbsp;
          {/* {record.profileStatus === '填写中' && (
            <>
              <a onClick={() => handleOperate(record, '提交')}>提交</a>
            </>
          )} */}
          {record.profileStatus === '填写中' ? (
            <a onClick={() => handleOperate(record, '提交')}>提交</a>
          ) : (
            <span style={{ color: 'darkgray' }}>提交</span>
          )}
          &nbsp;&nbsp;
          <a onClick={() => hanldleCopy(record)}>复制</a>&nbsp;&nbsp;
        </div>
      ),
    },
  ];

  const onChangePagination = (pagination: any) => {
    setPageNo(pagination.current);
    setPageSize(pagination.pageSize);
  };

  return (
    <PageContainer>
      <div className={styles['form-body']}>
        <ProForm
          form={form}
          layout="horizontal"
          submitter={false}
          initialValues={{
            activityId: '',
            onlineCode: '',
            activityGroup: '',
            activityGroupRound: '',
            activityStartTime: null,
            activityEndTime: null,
            activity: '',
            productIdRule: '',
            productIdBackupEx: '',
          }}
        >
          <ProForm.Group>
            <ProFormText
              labelCol={{ span: 9 }}
              width="sm"
              name="activityId"
              label="活动定义"
              placeholder="请输入"
            />
            <ProFormText
              labelCol={{ span: 9 }}
              width="sm"
              name="onlineCode"
              label="宅急送优惠CODE"
              placeholder="请输入"
            />
            <ProFormText
              labelCol={{ span: 9 }}
              width="sm"
              name="activityGroup"
              label="活动组"
              placeholder="请输入"
            />
            <ProFormText
              labelCol={{ span: 9 }}
              width="sm"
              name="activityGroupRound"
              label="活动组批次"
              placeholder="请输入"
            />

            <ProFormDateTimePicker
              labelCol={{ span: 9 }}
              width="sm"
              label="活动结束时间晚于"
              name="activityStartTime"
              fieldProps={{ format: 'YYYY-MM-DD HH:mm:ss' }}
            />
            <ProFormDateTimePicker
              labelCol={{ span: 9 }}
              width="sm"
              label="活动结束时间早于"
              name="activityEndTime"
              fieldProps={{ format: 'YYYY-MM-DD HH:mm:ss' }}
            />
            <ProFormText
              labelCol={{ span: 9 }}
              width="sm"
              name="activity"
              label="劵名"
              placeholder="请输入"
            />
            <ProFormText
              labelCol={{ span: 9 }}
              width="sm"
              name="productIdRule"
              label="产品ID"
              placeholder="请输入"
            />

            <ProFormText
              labelCol={{ span: 9 }}
              width="sm"
              name="productIdBackupEx"
              label="后备产品码"
              placeholder="请输入"
            />
            {/* <ProFormSelect
              labelCol={{ span: 9 }}
              width="sm"
              name="couponCategory"
              label="券名"
              options={[]}
              placeholder=""
            />
            <ProFormSelect
              mode="multiple"
              labelCol={{ span: 9 }}
              width="sm"
              name="profileStatus"
              label="劵状态"
              options={ENU_PROFILE_STATUS}
              placeholder=""
            /> */}
          </ProForm.Group>
        </ProForm>
        <div className={styles['query-body']}>
          <Button
            style={{ marginLeft: 16 }}
            onClick={() => {
              setPageNo(1);
              setPageSize(20);
              getList();
            }}
            type="primary"
          >
            查询
          </Button>
        </div>
      </div>

      <div style={{ float: 'right', marginTop: 16, marginBottom: 16 }}>
        <Button onClick={() => hanldleAdd()} type="primary">
          新增
        </Button>
      </div>
      <Table
        // @ts-ignore
        columns={columns}
        scroll={{ x: 1500 }}
        loading={spining}
        dataSource={dataSource}
        onChange={onChangePagination}
        pagination={{
          current: pageNo,
          pageSize,
          total,
          showSizeChanger: true,
          showTotal: (totals) => `共 ${totals} 条`,
        }}
      />
    </PageContainer>
  );
};

export default ProfileList;
